//
//  UmbrellaService.swift
//  ShareUmbrella
//
//  Created by niupark on 2017/9/13.
//  Copyright © 2017年 尧尚信息科技. All rights reserved.
//

import UIKit
import YSKit
import SwiftyJSON
import RxSwift

let Umbrella = UmbrellaService.sharedInstance

class UmbrellaService: NSObject {
    
    static let sharedInstance = UmbrellaService()
    private var timer:Timer?
    //附近的用户
    let nearbyUsers:Variable<JSON?> = Variable(nil)
    let nearbyAskForHelpers:Variable<JSON?> = Variable(nil)
    let nearbyAcceptHelpers:Variable<JSON?> = Variable(nil)
    let currentAccepHelper: Variable<JSON?> =  Variable(nil) //当前帮助者位置信息
    let currentAskForHelper: Variable<JSON?> =  Variable(nil) //当前求助者位置信息

    private override init(){
        super.init()
        
        //监听用户登录操作
        _  = Auth.isLogin.asObservable().takeUntil(self.rx.deallocated).subscribe(onNext: { [weak self] (isLogin) in
            guard let `self` = self else {
                return
            }
            if isLogin {
                self.startRefreshNearbyUsers()
            }else {
                self.stopRefresh()
            }
            
        })

        
        self.startRefreshNearbyUsers()
    }
    
    private func startRefreshNearbyUsers() {
        guard let _ = self.timer else {
            
            //5s更新一次附近用户的信息
            self.timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true, block: { (timer) in
                
                
                guard let location = Location.location.value, Auth.isLogin.value else {
                    return
                }
                
                //获取所有用户
                _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(UserAPI.nearbyUsers(token: Auth.token, latitude: location.coordinate.latitude, longitude: location.coordinate.longitude))).subscribe(onNext: { [weak self] (data) in
                    //
                    guard let `self` = self, let `data` = data else {
                        return
                    }
                    self.nearbyUsers.value = data["data"]
                    
                    //求助者和帮助者
                    data["data"].arrayValue.forEach({ (json) in
                        if let userId = json["userId"].string, let user =  User.statusInfo.value?.info {
                            //帮助者
                            if let id = user["acceptHelpUser"]["userId"].string , id == userId {
                                self.currentAccepHelper.value = json
                            }else if let id = user["askForHelpUser"]["userId"].string, id == userId {
                                //求助者
                                self.currentAskForHelper.value = json
                            }
                        }

                    })

                    print("获取周围用户->成功")
                    
                    }, onError: {(ErrorType) in
                        print("获取求助者用户->失败")
                        
                })

                //获取求助者位置
                _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(UserAPI.nearbyAskForHelpers(token: Auth.token, latitude: location.coordinate.latitude, longitude: location.coordinate.longitude))).subscribe(onNext: { [weak self] (data) in
                    //
                    guard let `self` = self, let `data` = data else {
                        return
                    }
                    self.nearbyAskForHelpers.value = data["data"]
                    print("获取周围求助者->成功")
                    
                    }, onError: {(ErrorType) in
                        print("获取求助者信息->失败")
                        
                })

                //获取提供帮助者
                _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(UserAPI.nearbyAcceptHelpers(token: Auth.token, latitude: location.coordinate.latitude, longitude: location.coordinate.longitude))).subscribe(onNext: { [weak self] (data) in
                    //
                    guard let `self` = self, let `data` = data else {
                        return
                    }
                    self.nearbyAcceptHelpers.value = data["data"]
                    print("获取周围求助者->成功")
                    
                    }, onError: {(ErrorType) in
                        print("获取求助者信息->失败")
                        
                })
                
            })
            self.timer?.fire()
            return
        }
        
    }
    private func  stopRefresh() {
        guard let t = self.timer else {
            return
        }
        
        t.invalidate()
        self.timer = nil
    }
    
}
